<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\unit\controller;

use think\Controller;
use think\Db;
use think\Cache;

class Base extends Controller
{
	public $compnay = [];
	public $compnay_id = 0;
	public function _initialize()
    {
    	
		$this->isLogin();
		
    }
    
    //首页
    public function index() {
		
		return $this->out();
		
	}
	
	public function _empty() {
		return $this->out(request()->action());
	}
	
	protected function out($action = '') {
		
		$action = $action ?: request()->action();
		$this->assign('JSFILE', '../template/'.request()->module().'/'.strtolower(request()->controller()).'/'.$action.'.js');
		$this->assign('action',$action);
		$this->assign('company',$this->company);
		
		return $this->fetch($action);
		
	}
	
	protected function popup($action = '') {
		
		$this->assign('notPopup',0);
		
		return $this->out($action);
		
	}
	
    //检查登录
    protected function isLogin() {
		
		$this->company_id = StrDecrypt(cookie('company_id'));
		
		if(!$this->company_id && request()->controller() != 'Login') {
			return $this->redirect('login/index');
		}
		$this->company = Db::name('company')->where('company_id',$this->company_id)->find();
		$this->assign('company',$this->company);
//		halt($this->user);
		
	}
	
	//列表
	public function datas() {
		
		$page = input('param.page',1);
		$where = $this->search();
		$where['c.company_id'] = $this->company['company_id'];

		$field = $this->field ?: 'm.*';
		
		$data['list'] = $this->joins()->where($where)->whereNull('m.delete_time')->order('m.'.$this->id.' DESC')->fetchSql(0)->field($field)->limit(10)->page($page)->select();
		$data['count'] = $this->joins()->where($where)->whereNull('m.delete_time')->count();
		
		return $this->apiout($data);
		
	}
	
	//列表
	public function all() {
		
		$where = [];
		if($this->joins || $this->join) {
			$where['c.company_id'] = $this->company_id;
		} else {
			$where['company_id'] = $this->company_id;
		}
		$field = $this->field ?: 'm.*';
		
		$list = $this->joins()->where($where)->whereNull('m.delete_time')->order('m.'.$this->id.' DESC')->fetchSql(0)->field('m.*')->select();
		
		return $this->apiout($list);
		
	}
	
	//连接共用
	protected function joins() {
		
		$Query = Db::name($this->table)->alias('m')->field($this->field);
		if($this->join || $this->joins) {
			
			$joins = $this->joins ?: [$this->join];
			foreach($joins AS $join) {
				$Query->join($join[0],$join[1],$join[2]);
			}
		}
		
		return $Query;
	}
	
	protected function _op() {
		$op = input('param.op');
		if(in_array($op, ['search','bind','unbind','entrust']) ) {
			$this->assign('notPopup',0);
		}
		$this->assign('op',$op);
	}
	
	//搜索
	protected function search() {
		//搜索
		$where = $options = [];
		$P = input('param.');
		if($P) {
			foreach($P AS $key=>$val) {
				
				if( $val && !in_array($key, ['op','page']) ){
					
					if(StrFind($key,'-')) {
						$keys = explode('-',$key);
						$wkey = $keys[0].'.'.$keys[1];
						$key = $keys[1];
					} else {
						$wkey = 'm.'.$key;
					}
					
					if($key == 'start_date'){
						$where[$wkey] = ['>=',$val];
					} elseif($key =='end_date'){
						$where[$wkey] = ['<=',$val];
					} elseif( in_array($key, ['name','number','phone','order_no','insurance_company']) ) {
						$where[$wkey] = ['LIKE','%'.$val.'%'];
					} elseif( StrFind($key,'_time') ) {
						$where[$wkey] = $val;
					} else {
						$where[$wkey] = $val;
					}
					
					$options[$key] = $where[$wkey];
				}
			}
		}
		$this->options($options);
		return $where;
		
	}
    
    public function detail() {
		
		$id = input('param.'.$this->id);
		$item = $this->joins()->where('m.'.$this->id,$id)->find();
		$item = $this->options($item);
		
		return $this->apiout($item);
		
	}
	
	//添加
	public function add() {
		
		if(request()->isPost()) {
			
			$data = $this->data();
			$id = Db::name($this->table)->insertGetId($data);
			
			//更新缓存
			return $this->res($id?1:0 ,[ 'msg' => '','data'=>$id],'car/cost');
		}
		//选项 
		$this->options();
		
		return $this->out();
		
	}
	
	public function edit() {
		
		$id = input('param.'.$this->id.'/d');
		
		if(!$id) {
			return $this->error('入口非法，请重试');
		}
		//提交
		if(request()->isPost()) {
			
			$data = $this->data();
			$rslt = Db::name($this->table)->where($this->id,$id)->update($data);
				
			return $this->res($rslt,['修改并保存成功','内容未修改或网络问题，请联系开发者 i@fazi.me'],1);
			
		}
		//连接查询
		$item = $this->joins()->where($this->id,$id)->find();
		
		//选项
		$item = $this->options($item);
		$this->assign('item',$item);
//halt($item);
		return $this->out('add');
		
	}
	
	//删除 
	public function delete() {
		
		$id = input('post.id/a');
		
		if($id) {
			if(is_array($id)) $id = implode(',',$id);
			$rslt = Db::name($this->table)->whereIn($this->id,$id)->setField('delete_time',time());
		}
		
		return $this->res($rslt);
		
	}

	//详情
   public function details() {

        $id = input('param.'.$this->id);
        $item = $this->joins()->where('m.'.$this->id,$id)->find();

        $item = $this->options($item);

        $this->assign('item',$item);
        $this->_op();
        return $this->out();

    }
	
	//状态 
	public function state() {
		
		$id = input('post.id/d');
		$state = input('post.state/d');
		
		if($id) {
			$key = $this->state ?: 'state';
			$rslt = Db::name($this->table)->where($this->id,$id)->fetchSql(0)->setField($key,$state);
		}
		
		return $this->res($rslt);
		
	}
	
	//上传
	protected function upload($data){
		
    	// 获取表单上传文件
	    $files = request()->file();
	    if($files){
		    foreach($files as $name => $file){
		        // 移动到框架应用根目录/public/uploads/ 目录下
		        $info = $file->move(UPLOAD_PATH);
		        if($info){
		            // 成功上传后 获取上传信息
		            // 输出 42a79759f284b767dfcb2a0197904287.jpg
		            $data[$name] = $info->getSaveName(); 
		        }else{
		            // 上传失败获取错误信息
	//	            echo $file->getError();
		        }    
		    }
	    }
	    return $data;
	}
	
	//更新缓存
	protected function clearcache($rslt) {
		if($rslt) Cache::rm($this->table);
	}
	
	//DATA
	protected function data() {
		$P = input('post.');
		
		//ID
		if( isset($P['id']) ) {
			$P[$this->id] = $P['id'];
			unset($P['id']);
		}
		//数据整理
		$this->validData( $P );#验证
		$data = $this->parseData( $P );
		
		//数组值变SET
		if($data[$this->id]) {
			
		} else {
			unset($data[$this->id]);
		}
		//上传图片
		$data = $this->upload($data);
		
		return $data;
	}
	
	protected function validData($data = []) {
		return true;
	}
	protected function parseData($data = []) {
		$data = array_map('Arr2Set',$data);
		return $data;
	}
	protected function options($item = []) {
		return $item;
	}
    
    /**
	* 自定义响应
	* @param undefined $success
	* @param undefined $url
	* 
	* @return
	*/
	protected function res($success,$msg = '',$url = '',$cache = '') {
		
		if($success){
			$error = 0;
			//清理缓存
			$cache && cache($cache,NULL);
		} else {
			$error = 1;
		}
		
		return $this->msg($url,$error,$msg);
	}
    
    /**
	* 操作结束后提示
	* @param str $url 
	* @param int $error 
	* @param str $msg
	* @param int $sec
	* 
	* @return
	*/
	public function msg($url = '', $error = 0, $msg = '',$sec = 2) {
		
		$data = [];
		//MSG 为数组时可带数据
		if(is_array( $msg )) {
			$data = $msg['data'];
			$msg = $msg['msg'][$error] ?: $msg[$error];
		}
		if(is_numeric($url)){
			$data['url'] = $url;
			$url = '';
		}

		$msg = $msg ? lang($msg) :'';#语言包
		
		if( request()->isAjax() ){

			if($error){
				return $this->error($msg,$url,$data,$sec);
			} else {
				return $this->success($msg,$url,$data,$sec);
			}
			
		} else {
			
			//直接跳转
			if($sec == 0) {
				return $this->redirect($url);
			}
			
//			$this->assign('JSFILE', '../application/index/view/common/msg.js');
//			
			$this->assign('url',$url);
			$this->assign('msg',$msg);
			$this->assign('sec',$sec);
			$this->assign('error',$error);
			return $this->fetch('common/msg');
			
		}
	}
	
	protected function CF($url,$postdata = [],$isZip = 0) {
		
		ob_start();
		$hander = curl_init();
		curl_setopt($hander, CURLOPT_HTTPHEADER , $headerArr );
		curl_setopt($hander, CURLOPT_URL,$url); 
		curl_setopt($hander, CURLOPT_FOLLOWLOCATION,1); 
		curl_setopt($hander, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );

		if ($postdata) {
			curl_setopt( $hander, CURLOPT_POST, 1 );
			curl_setopt( $hander, CURLOPT_POSTFIELDS, is_array($postdata) ? http_build_query($postdata) : $postdata );
		} else {
			curl_setopt( $hander, CURLOPT_CUSTOMREQUEST, 'GET');
		}

		curl_setopt($hander, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查  
	    curl_setopt($hander, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在 
		$isZip && curl_setopt($hander, CURLOPT_ENCODING, "gzip");
		curl_setopt($hander, CURLOPT_HEADER,0);
//		curl_setopt($hander, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:8.8.8.8')); //构造IP
		curl_setopt($hander, CURLOPT_RETURNTRANSFER,1);//以数据流的方式返回数据,当为false是直接显示出来
		
		curl_setopt($hander,CURLOPT_TIMEOUT,60);
		curl_setopt($hander,CURLOPT_CONNECTTIMEOUT,60);
		$content = curl_exec($hander);
		$info = curl_getinfo($hander);
//		halt($content);
	
//		curl_close($hander);
		$rslt = [$content,$info];
//		halt($rslt);
		Return $rslt;
	}
	
	
	protected function apiout($success,$data = [],$msg = '',$url = '') {
		
		$data = empty($data) ? $success : $data;
		if($success){
			$info = ['code'=>1, 'data' => $data ];
		} else {
			$info = ['code'=>0, 'data' => $msg ];
		}
		
		return json($info);
	}
	
}
